﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using LabManager.Controller.Views;
using LabManager.Models;
using LabManager.Controller;
using System.IO.Ports;
using LabLibary;

namespace LabManager
{
    public partial class frmMain : XtraForm, ConnectView
    {

        #region Thuoc Tinh
        public string CurrentPort
        {
            get { return rdgComPorts.Properties.Items[rdgComPorts.SelectedIndex].Value.ToString(); }
            set { rdgComPorts.Properties.Items[rdgComPorts.SelectedIndex].Value = value; }
        }

        public string CurrentPortName
        {
            get { return rdgComPorts.Properties.Items[rdgComPorts.SelectedIndex].Description.ToString(); }
        }

        #endregion


        CauHinhController _cauHinhController = new CauHinhController();
        List<ComportInfo> _lstComInfo = new List<ComportInfo>();
        bool _isLoop01 = false;
        bool _isLoop02 = false;
        bool _isLoop03 = false;
        bool _isLoop04 = false;
        bool _isLoop05 = false;
        bool _isLoop06 = false;
        bool _isLoop07 = false;
        bool _isLoop08 = false;

        List<ObjResults> LstObjResuts = new List<ObjResults>();
        MainController _controller = new MainController();


        /// <summary>
        /// Serial Port
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private SerialPort comport01 = new SerialPort();
        private SerialPort comport02 = new SerialPort();
        private SerialPort comport03 = new SerialPort();
        private SerialPort comport04 = new SerialPort();
        private SerialPort comport05 = new SerialPort();
        private SerialPort comport06 = new SerialPort();
        private SerialPort comport07 = new SerialPort();
        private SerialPort comport08 = new SerialPort();


        #region Cac Ham
        void ClearValue(int portNumber =0 )
        {
            try
            {
                if (portNumber == 0)
                {
                    txtTenMayXN01.Text = "";
                    txtThongSo01.Text = "";
                    SetTrangThai(txtTrangThai01, "");
                    return;
                }
                if (portNumber == 1)
                {
                    txtTenMayXN02.Text = "";
                    txtThongSo02.Text = "";
                    SetTrangThai(txtTrangThai02, "");
                    return;
                }
                if (portNumber == 2)
                {
                    txtTenMayXN03.Text = "";
                    txtThongSo03.Text = "";
                    SetTrangThai(txtTrangThai03, "");
                    return;
                }
                if (portNumber == 3)
                {
                    txtTenMayXN04.Text = "";
                    txtThongSo04.Text = "";
                    SetTrangThai(txtTrangThai04, "");
                    return;
                }
                if (portNumber == 4)
                {
                    txtTenMayXN05.Text = "";
                    txtThongSo05.Text = "";
                    SetTrangThai(txtTrangThai05, "");
                    return;
                }
                if (portNumber == 5)
                {
                    txtTenMayXN06.Text = "";
                    txtThongSo06.Text = "";
                    SetTrangThai(txtTrangThai06, "");
                    return;
                }
                if (portNumber == 6)
                {
                    txtTenMayXN07.Text = "";
                    txtThongSo07.Text = "";
                    SetTrangThai(txtTrangThai07, "");
                    return;
                }
                if (portNumber == 7)
                {
                    //Clear all
                    txtTenMayXN08.Text = "";
                    txtThongSo08.Text = "";
                    SetTrangThai(txtTrangThai08, "");
                    return;
                }
            }
            catch { }
        }

        void SetInfo(int portNumber, ComportInfo comInfo)
        {
            try
            {
                string strConfigInfo = comInfo.portName + ", " + comInfo._Baurate + ", " + comInfo._DataBits + ", " + comInfo._Parity + ", " + comInfo._StopBits + ", " + comInfo._HandShaking;

                if (portNumber == 0)
                {
                    txtTenMayXN01.Text = comInfo.LabMachineName;
                    txtThongSo01.Text = strConfigInfo;
                    SetTrangThai(txtTrangThai01, "Đóng kết nối");
                    return;
                }
                if (portNumber == 1)
                {
                    txtTenMayXN02.Text = comInfo.LabMachineName;
                    txtThongSo02.Text = strConfigInfo;
                    SetTrangThai(txtTrangThai02, "Đóng kết nối");
                    return;
                }
                if (portNumber == 2)
                {
                    txtTenMayXN03.Text = comInfo.LabMachineName;
                    txtThongSo03.Text = strConfigInfo;
                    SetTrangThai(txtTrangThai03, "Đóng kết nối");
                    return;
                }
                if (portNumber == 3)
                {
                    txtTenMayXN04.Text = comInfo.LabMachineName;
                    txtThongSo04.Text = strConfigInfo;
                    SetTrangThai(txtTrangThai04, "Đóng kết nối");
                    return;
                }
                if (portNumber == 4)
                {
                    txtTenMayXN05.Text = comInfo.LabMachineName;
                    txtThongSo05.Text = strConfigInfo;
                    SetTrangThai(txtTrangThai05, "Đóng kết nối");
                    return;
                }
                if (portNumber == 5)
                {
                    txtTenMayXN06.Text = comInfo.LabMachineName;
                    txtThongSo06.Text = strConfigInfo;
                    SetTrangThai(txtTrangThai06, "Đóng kết nối");
                    return;
                }
                if (portNumber == 6)
                {
                    txtTenMayXN07.Text = comInfo.LabMachineName;
                    txtThongSo07.Text = strConfigInfo;
                    SetTrangThai(txtTrangThai07, "Đóng kết nối");
                    return;
                }
                if (portNumber == 7)
                {
                    txtTenMayXN08.Text = comInfo.LabMachineName;
                    txtThongSo08.Text = strConfigInfo;
                    SetTrangThai(txtTrangThai08, "Đóng kết nối");
                    return;
                }
            }
            catch { }
        }

        void SetTrangThai(TextEdit txtStatus, string status)
        {
            txtStatus.Text = status;
        }

        void SetActiveColor(TextEdit txt01, TextEdit txt02, TextEdit txt03)
        {
            txt01.ForeColor = System.Drawing.Color.Blue;
            txt02.ForeColor = System.Drawing.Color.Blue;
            txt03.ForeColor = System.Drawing.Color.Blue;
        }

        void SetDeActiveColor(TextEdit txt01, TextEdit txt02, TextEdit txt03)
        {
            txt01.ForeColor = System.Drawing.Color.Red;
            txt02.ForeColor = System.Drawing.Color.Red;
            txt03.ForeColor = System.Drawing.Color.Red;
        }

        void InitConfig()
        {
            try
            {
                _lstComInfo = _cauHinhController.LoadConfig();

                int i = 0;
                foreach (ComportInfo comInfo in _lstComInfo)
                {
                    SetInfo(i, comInfo);
                    i++;
                }
            }
            catch { }
        }

        bool CheckPortIsOpened()
        {
            bool result = false;
            int position = rdgComPorts.SelectedIndex;
            if (position == 0)
            {
                if (comport01.IsOpen)
                    result = true;
            }
            if (position == 1)
            {
                if (comport02.IsOpen)
                    result = true;
            }

            return result;
        }

        bool CheckAllPorts()
        {

            for (int i = 0; i < rdgComPorts.Properties.Items.Count; i++)
            {
                switch (i)
                {
                    case 0:
                        if (comport01.IsOpen)
                            return true;
                        break;

                    case 1:
                        if (comport02.IsOpen)
                            return true;
                        break;

                    case 2:
                        if (comport03.IsOpen)
                            return true;
                        break;

                    case 3:
                        if (comport04.IsOpen)
                            return true;
                        break;

                    case 4:
                        if (comport05.IsOpen)
                            return true;
                        break;

                    case 5:
                        if (comport06.IsOpen)
                            return true;
                        break;

                    case 6:
                        if (comport07.IsOpen)
                            return true;
                        break;

                    case 7:
                        if (comport08.IsOpen)
                            return true;
                        break;
                }
            }

            return false;
        }

        void KetNoiTatCa()
        {
            for (int i = 0; i < rdgComPorts.Properties.Items.Count; i++)
            {
                if (_lstComInfo[i] != null)
                {
                    KetNoi(i);
                }
            }
        }

        #endregion


        #region Events Forms

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            rdgComPorts.SelectedIndex = 0;
            InitConfig();

            dtNgayLamViec.DateTime = DateTime.Now;

            grdResults.DataSource = LstObjResuts;


            KetNoiTatCa();


        }

        private void btnCauHinh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {

                if (CheckPortIsOpened())
                {
                    MessageBox.Show("Không thể cấu hình " + CurrentPortName + " đang hoạt động.");
                    return;
                }

                frmCauHinh fCauHinh = new frmCauHinh();
                fCauHinh.ComportNumber = CurrentPortName;
                fCauHinh.ComportValue = CurrentPort;

                fCauHinh.Show();

                fCauHinh.FormClosed += new FormClosedEventHandler(fCauHinh_FormClosed);
            }
            catch
            {
                MessageBox.Show("Chọn cổng cần cấu hình.");
            }
        }

        void fCauHinh_FormClosed(object sender, FormClosedEventArgs e)
        {
            InitConfig();
        }

        private void btnDong_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (CheckAllPorts())
            {
                MessageBox.Show("Các cổng còn đang hoạt động. \n Vui lòng đóng các cổng trước.");
                return;
            }
            Close();
        }

        private void btnKetNoi_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            KetNoi(rdgComPorts.SelectedIndex);
        }

        private void btnClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DongKetNoi(rdgComPorts.SelectedIndex);
        }

        private void btnXoaCauHinh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            CauHinhController _cauhinhController = new CauHinhController();
            _cauhinhController._comportInfo = null;
            _cauhinhController.Save(rdgComPorts.SelectedIndex);
            ClearValue(rdgComPorts.SelectedIndex);
        }

        private void btnKetNoiAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            for (int i = 0; i < rdgComPorts.Properties.Items.Count; i++)
            {
                if (_lstComInfo[i] != null)
                {
                    KetNoi(i);
                }
            }
        }

        private void btnCloseAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            for (int i = 0; i < rdgComPorts.Properties.Items.Count; i++)
            {
                if (_lstComInfo[i] != null)
                {
                    DongKetNoi(i);
                }
            }
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            for (int i = 0; i < rdgComPorts.Properties.Items.Count; i++)
            {
                if (_lstComInfo[i] != null)
                {
                    DongKetNoi(i);
                }
            }
        }
        #endregion



        void DongKetNoi(int position)
        {
            //////////////////////////////////////////////
            /// Cong-01
            #region Cong-01
            if (position == 0)
            {
                if (comport01.IsOpen)
                {
                    comport01.Close();
                    SetTrangThai(txtTrangThai01, "Đã đóng kết nối");
                    SetDeActiveColor(txtTenMayXN01, txtThongSo01, txtTrangThai01);
                    return;
                }
            }
            #endregion

            //////////////////////////////////////////////
            /// Cong-02
            #region Cong-02
            if (position == 1)
            {
                if (comport02.IsOpen)
                {
                    comport02.Close();
                    SetTrangThai(txtTrangThai02, "Đã đóng kết nối");
                    SetDeActiveColor(txtTenMayXN02, txtThongSo02, txtTrangThai02);
                    return;
                }
            }
            #endregion

            //////////////////////////////////////////////
            /// Cong-03
            #region Cong-03
            if (position == 2)
            {
                if (comport03.IsOpen)
                {
                    comport03.Close();
                    SetTrangThai(txtTrangThai03, "Đã đóng kết nối");
                    SetDeActiveColor(txtTenMayXN03, txtThongSo03, txtTrangThai03);
                    return;
                }
            }
            #endregion

            //////////////////////////////////////////////
            /// Cong-04
            #region Cong-04
            if (position == 3)
            {
                if (comport04.IsOpen)
                {
                    comport04.Close();
                    SetTrangThai(txtTrangThai04, "Đã đóng kết nối");
                    SetDeActiveColor(txtTenMayXN04, txtThongSo04, txtTrangThai04);
                    return;
                }
            }
            #endregion

            //////////////////////////////////////////////
            /// Cong-05
            #region Cong-05
            if (position == 4)
            {
                if (comport05.IsOpen)
                {
                    comport05.Close();
                    SetTrangThai(txtTrangThai05, "Đã đóng kết nối");
                    SetDeActiveColor(txtTenMayXN05, txtThongSo05, txtTrangThai05);
                    return;
                }
            }
            #endregion

            //////////////////////////////////////////////
            /// Cong-06
            #region Cong-06
            if (position == 5)
            {
                if (comport06.IsOpen)
                {
                    comport06.Close();
                    SetTrangThai(txtTrangThai06, "Đã đóng kết nối");
                    SetDeActiveColor(txtTenMayXN06, txtThongSo06, txtTrangThai06);
                    return;
                }
            }
            #endregion

            //////////////////////////////////////////////
            /// Cong-07
            #region Cong-07
            if (position == 6)
            {
                if (comport07.IsOpen)
                {
                    comport07.Close();
                    SetTrangThai(txtTrangThai07, "Đã đóng kết nối");
                    SetDeActiveColor(txtTenMayXN07, txtThongSo07, txtTrangThai07);
                    return;
                }
            }
            #endregion

            //////////////////////////////////////////////
            /// Cong-08
            #region Cong-08
            if (position == 7)
            {
                if (comport08.IsOpen)
                {
                    comport08.Close();
                    SetTrangThai(txtTrangThai08, "Đã đóng kết nối");
                    SetDeActiveColor(txtTenMayXN08, txtThongSo08, txtTrangThai08);
                    return;
                }
            }
            #endregion
        }

        void KetNoi(int position)
        {
            ///////////////////////////////////////////////////////////////////
            /// Cổng 01
            //////////////////////////////////////////////////////////////////
            #region Cong-01
            if (position == 0)
            {
                if (comport01.IsOpen)
                {
                    MessageBox.Show( comport01.PortName + " đang hoạt động");
                    return;
                }

                try
                {
                    comport01.PortName = _lstComInfo[position].portName;
                    comport01.BaudRate = _lstComInfo[position]._Baurate;

                    comport01.DataBits = _lstComInfo[position]._DataBits;
                    comport01.StopBits = _lstComInfo[position]._StopBits;
                    comport01.Parity = _lstComInfo[position]._Parity;

                    comport01.DtrEnable = true;
                    comport01.RtsEnable = true;

//                    comport01.Handshake = Handshake.None;

                }
                catch { 

                    MessageBox.Show("Cổng này chưa được cấu hình. \n Vui lòng cấu hình cổng này"); return; 
                }

                try
                {
                    // Open the port
                    comport01.Open();

                    SetTrangThai(txtTrangThai01, "Đang hoạt động...");
                    SetActiveColor(txtTenMayXN01, txtThongSo01, txtTrangThai01);
                    comport01.DataReceived += new SerialDataReceivedEventHandler(comport01_DataReceived);
                }
                catch { MessageBox.Show(comport01.PortName + " đang hoạt động");  }
            }


            #endregion


            ///////////////////////////////////////////////////////////////////
            /// Cổng 02
            //////////////////////////////////////////////////////////////////
            #region Cong-02
            if (position == 1)
            {
                if (comport02.IsOpen)
                {
                    MessageBox.Show(comport02.PortName + " đang hoạt động");
                    return;
                }

                try
                {
                    comport02.PortName = _lstComInfo[position].portName;
                    comport02.BaudRate = _lstComInfo[position]._Baurate;

                    comport02.DataBits = _lstComInfo[position]._DataBits;
                    comport02.StopBits = _lstComInfo[position]._StopBits;
                    comport02.Parity = _lstComInfo[position]._Parity;

                    comport02.DtrEnable = true;
                    comport02.RtsEnable = true;
                }
                catch { MessageBox.Show("Cổng này chưa được cấu hình. \n Vui lòng cấu hình cổng này"); return; }

                try
                {
                    // Open the port
                    comport02.Open();
                    SetTrangThai(txtTrangThai02, "Đang hoạt động...");
                    SetActiveColor(txtTenMayXN02, txtThongSo02, txtTrangThai02);
                    comport02.DataReceived += new SerialDataReceivedEventHandler(comport02_DataReceived);
                }
                catch { MessageBox.Show(comport02.PortName + " đang hoạt động"); }
            }
            #endregion

            ///////////////////////////////////////////////////////////////////
            /// Cổng 03
            //////////////////////////////////////////////////////////////////
            #region Cong-03
            if (position == 2)
            {

                if (comport03.IsOpen)
                {
                    MessageBox.Show(comport03.PortName + " đang hoạt động");
                    return;
                }

                try
                {
                    comport03.PortName = _lstComInfo[position].portName;
                    comport03.BaudRate = _lstComInfo[position]._Baurate;

                    comport03.DataBits = _lstComInfo[position]._DataBits;
                    comport03.StopBits = _lstComInfo[position]._StopBits;
                    comport03.Parity = _lstComInfo[position]._Parity;

                    comport03.DtrEnable = true;
                    comport03.RtsEnable = true;
                }
                catch { MessageBox.Show("Cổng này chưa được cấu hình. \n Vui lòng cấu hình cổng này"); return; }

                try
                {
                    // Open the port
                    comport03.Open();
                    SetTrangThai(txtTrangThai03, "Đang hoạt động...");
                    SetActiveColor(txtTenMayXN03, txtThongSo03, txtTrangThai03);
                    comport03.DataReceived += new SerialDataReceivedEventHandler(comport03_DataReceived);
                }
                catch { MessageBox.Show(comport03.PortName + " đang hoạt động"); }
            }
            #endregion


            ///////////////////////////////////////////////////////////////////
            /// Cổng 04
            //////////////////////////////////////////////////////////////////
            #region Cong-04
            if (position == 3)
            {

                if (comport04.IsOpen)
                {
                    MessageBox.Show(comport04.PortName + " đang hoạt động");
                    return;
                }

                try
                {
                    comport04.PortName = _lstComInfo[position].portName;
                    comport04.BaudRate = _lstComInfo[position]._Baurate;

                    comport04.DataBits = _lstComInfo[position]._DataBits;
                    comport04.StopBits = _lstComInfo[position]._StopBits;
                    comport04.Parity = _lstComInfo[position]._Parity;

                    comport04.DtrEnable = true;
                    comport04.RtsEnable = true;
                }
                catch { MessageBox.Show("Cổng này chưa được cấu hình. \n Vui lòng cấu hình cổng này"); return; }

                try
                {
                    // Open the port
                    comport04.Open();
                    SetTrangThai(txtTrangThai04, "Đang hoạt động...");
                    SetActiveColor(txtTenMayXN04, txtThongSo04, txtTrangThai04);
                    comport04.DataReceived += new SerialDataReceivedEventHandler(comport04_DataReceived);
                }
                catch { MessageBox.Show(comport04.PortName + " đang hoạt động"); }
            }
            #endregion


            ///////////////////////////////////////////////////////////////////
            /// Cổng 05
            //////////////////////////////////////////////////////////////////
            #region Cong-05
            if (position == 4)
            {

                if (comport05.IsOpen)
                {
                    MessageBox.Show(comport05.PortName + " đang hoạt động");
                    return;
                }

                try
                {
                    comport05.PortName = _lstComInfo[position].portName;
                    comport05.BaudRate = _lstComInfo[position]._Baurate;

                    comport05.DataBits = _lstComInfo[position]._DataBits;
                    comport05.StopBits = _lstComInfo[position]._StopBits;
                    comport05.Parity = _lstComInfo[position]._Parity;

                    comport05.DtrEnable = true;
                    comport05.RtsEnable = true;
                }
                catch { MessageBox.Show("Cổng này chưa được cấu hình. \n Vui lòng cấu hình cổng này"); return; }

                try
                {
                    // Open the port
                    comport05.Open();
                    SetTrangThai(txtTrangThai05, "Đang hoạt động...");
                    SetActiveColor(txtTenMayXN05, txtThongSo05, txtTrangThai05);
                    comport05.DataReceived += new SerialDataReceivedEventHandler(comport05_DataReceived);
                }
                catch { MessageBox.Show(comport05.PortName + " đang hoạt động"); }
            }
            #endregion


            ///////////////////////////////////////////////////////////////////
            /// Cổng 06
            //////////////////////////////////////////////////////////////////
            #region Cong-06
            if (position == 5)
            {

                if (comport06.IsOpen)
                {
                    MessageBox.Show(comport06.PortName + " đang hoạt động");
                    return;
                }

                try
                {
                    comport06.PortName = _lstComInfo[position].portName;
                    comport06.BaudRate = _lstComInfo[position]._Baurate;

                    comport06.DataBits = _lstComInfo[position]._DataBits;
                    comport06.StopBits = _lstComInfo[position]._StopBits;
                    comport06.Parity = _lstComInfo[position]._Parity;

                    comport06.DtrEnable = true;
                    comport06.RtsEnable = true;
                }
                catch { MessageBox.Show("Cổng này chưa được cấu hình. \n Vui lòng cấu hình cổng này"); return; }

                try
                {
                    // Open the port
                    comport06.Open();
                    SetTrangThai(txtTrangThai06, "Đang hoạt động...");
                    SetActiveColor(txtTenMayXN06, txtThongSo06, txtTrangThai06);
                    comport06.DataReceived += new SerialDataReceivedEventHandler(comport06_DataReceived);
                }
                catch { MessageBox.Show(comport06.PortName + " đang hoạt động"); }
            }
            #endregion


            ///////////////////////////////////////////////////////////////////
            /// Cổng 07
            //////////////////////////////////////////////////////////////////
            #region Cong-07
            if (position == 6)
            {

                if (comport07.IsOpen)
                {
                    MessageBox.Show(comport07.PortName + " đang hoạt động");
                    return;
                }

                try
                {
                    comport07.PortName = _lstComInfo[position].portName;
                    comport07.BaudRate = _lstComInfo[position]._Baurate;

                    comport07.DataBits = _lstComInfo[position]._DataBits;
                    comport07.StopBits = _lstComInfo[position]._StopBits;
                    comport07.Parity = _lstComInfo[position]._Parity;

                    comport07.DtrEnable = true;
                    comport07.RtsEnable = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    //MessageBox.Show("Cổng này chưa được cấu hình. \n Vui lòng cấu hình cổng này"); 
                    return; 
                }

                try
                {
                    // Open the port
                    comport07.Open();
                    SetTrangThai(txtTrangThai07, "Đang hoạt động...");
                    SetActiveColor(txtTenMayXN07, txtThongSo07, txtTrangThai07);
                    comport07.DataReceived += new SerialDataReceivedEventHandler(comport07_DataReceived);
                }
                catch { MessageBox.Show(comport07.PortName + " đang hoạt động"); }
            }
            #endregion


            ///////////////////////////////////////////////////////////////////
            /// Cổng 08
            //////////////////////////////////////////////////////////////////
            #region Cong-08
            if (position == 7)
            {

                if (comport08.IsOpen)
                {
                    MessageBox.Show(comport08.PortName + " đang hoạt động");
                    return;
                }

                try
                {
                    comport08.PortName = _lstComInfo[position].portName;
                    comport08.BaudRate = _lstComInfo[position]._Baurate;

                    comport08.DataBits = _lstComInfo[position]._DataBits;
                    comport08.StopBits = _lstComInfo[position]._StopBits;
                    comport08.Parity = _lstComInfo[position]._Parity;

                    comport08.DtrEnable = true;
                    comport08.RtsEnable = true;
                }
                catch { MessageBox.Show("Cổng này chưa được cấu hình. \n Vui lòng cấu hình cổng này"); return; }

                try
                {
                    // Open the port
                    comport08.Open();
                    SetTrangThai(txtTrangThai08, "Đang hoạt động...");
                    SetActiveColor(txtTenMayXN08, txtThongSo08, txtTrangThai08);
                    comport08.DataReceived += new SerialDataReceivedEventHandler(comport08_DataReceived);
                }
                catch { MessageBox.Show(comport08.PortName + " đang hoạt động"); }
            }
            #endregion

        }
        

        #region Comport-01 -- Receiving data
        void comport01_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            txtTrangThai01.Invoke(new EventHandler(delegate
            {
                txtTrangThai01.Text = "Đang nhận dữ liệu...";
            }));

            List<ObjResults> _lstObjResult = new List<ObjResults>();

            if (!comport01.IsOpen)
            {
                MessageBox.Show("Comport was closed.");
                return;
            }

            try
            {
                // Read all the data waiting in the buffer
                string data = comport01.ReadExisting();

                //Dubug Data
                rtxtResult01.Invoke(new EventHandler(delegate
                {
                    rtxtResult01.AppendText(data + "@END@");
                }));

                _lstObjResult = LabExtractData.DoData(_lstComInfo[0].LabMachineName, data, "port01");

                if (_lstObjResult != null)
                {
                    LstObjResuts = _lstObjResult;

                    foreach (ObjResults _rObject in LstObjResuts)
                    {
                       _controller.Save(_rObject);
                    }
                }


                //Auto send data to Comport
                if (LabMachines.lstMayXn2Chieu.Contains(_lstComInfo[0].LabMachineName))
                {
                    char[] c = data.ToCharArray();

                    if (Convert.ToInt32(c[0]).ToString() == "5")
                        _isLoop01 = true;

                    if (Convert.ToInt32(c[0]).ToString() == "4")
                        _isLoop01 = false;

                    System.Threading.Thread.Sleep(200);
                    if (_isLoop01)
                        LabCommon.AutoSend(comport01);
                }

                grdResults.Invoke(new EventHandler(delegate
                {
                    grdResults.DataSource = LstObjResuts;
                }));

            }
            catch { }

            txtTrangThai01.Invoke(new EventHandler(delegate
            {
                txtTrangThai01.Text = "Đang hoạt động...";
            }));
        }
        #endregion


        #region Comport02 - Receiving data
        void comport02_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            txtTrangThai02.Invoke(new EventHandler(delegate
            {
                txtTrangThai02.Text = "Đang nhận dữ liệu...";
            }));

            List<ObjResults> _lstObjResult = new List<ObjResults>();

            if (!comport02.IsOpen)
            {
                MessageBox.Show("Comport was closed.");
                return;
            }

            try
            {
                // Read all the data waiting in the buffer
                string data = comport02.ReadExisting();

                //Dubug Data
                rtxtResult01.Invoke(new EventHandler(delegate
                {
                    rtxtResult01.AppendText(data + "@END@");
                }));


                _lstObjResult = LabExtractData.DoData(_lstComInfo[1].LabMachineName, data, "port02");

                if (_lstObjResult != null)
                {
                    LstObjResuts = _lstObjResult;

                    foreach (ObjResults _rObject in LstObjResuts)
                    {
                        _controller.Save(_rObject);
                    }
                }


                //Auto send data to Comport
                if (LabMachines.lstMayXn2Chieu.Contains(_lstComInfo[1].LabMachineName))
                {
                    char[] c = data.ToCharArray();

                    if (Convert.ToInt32(c[0]).ToString() == "5")
                        _isLoop02 = true;

                    if (Convert.ToInt32(c[0]).ToString() == "4")
                        _isLoop02 = false;

                    System.Threading.Thread.Sleep(200);
                    if (_isLoop02)
                        LabCommon.AutoSend(comport02);
                }

                grdResults.DataSource = LstObjResuts;
            }
            catch { }

            txtTrangThai02.Invoke(new EventHandler(delegate
            {
                txtTrangThai02.Text = "Đang hoạt động...";
            }));
        }
        #endregion


        #region Comport03 - Receiving data
        void comport03_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            txtTrangThai03.Invoke(new EventHandler(delegate
            {
                txtTrangThai03.Text = "Đang nhận dữ liệu...";
            }));

            List<ObjResults> _lstObjResult = new List<ObjResults>();

            if (!comport03.IsOpen)
            {
                MessageBox.Show("Comport was closed.");
                return;
            }

            try
            {
                // Read all the data waiting in the buffer
                string data = comport03.ReadExisting();

                //Dubug Data
                rtxtResult01.Invoke(new EventHandler(delegate
                {
                    rtxtResult01.AppendText(data + "@END@");
                }));


                _lstObjResult = LabExtractData.DoData(_lstComInfo[2].LabMachineName, data, "port03");

                if (_lstObjResult != null)
                {
                    LstObjResuts = _lstObjResult;

                    foreach (ObjResults _rObject in LstObjResuts)
                    {
                        _controller.Save(_rObject);
                    }
                }


                //Auto send data to Comport
                if (LabMachines.lstMayXn2Chieu.Contains(_lstComInfo[2].LabMachineName))
                {
                    char[] c = data.ToCharArray();

                    if (Convert.ToInt32(c[0]).ToString() == "5")
                        _isLoop03 = true;

                    if (Convert.ToInt32(c[0]).ToString() == "4")
                        _isLoop03 = false;

                    System.Threading.Thread.Sleep(200);
                    if (_isLoop03)
                        LabCommon.AutoSend(comport03);
                }

                grdResults.DataSource = LstObjResuts;
            }
            catch { }

            txtTrangThai03.Invoke(new EventHandler(delegate
            {
                txtTrangThai03.Text = "Đang hoạt động...";
            }));
        }
        #endregion


        #region Comport04 - Receiving data
        void comport04_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            txtTrangThai04.Invoke(new EventHandler(delegate
            {
                txtTrangThai04.Text = "Đang nhận dữ liệu...";
            }));

            List<ObjResults> _lstObjResult = new List<ObjResults>();

            if (!comport04.IsOpen)
            {
                MessageBox.Show("Comport was closed.");
                return;
            }

            try
            {
                // Read all the data waiting in the buffer
                string data = comport04.ReadExisting();

                //Dubug Data
                rtxtResult01.Invoke(new EventHandler(delegate
                {
                    rtxtResult01.AppendText(data + "@END@");
                }));


                _lstObjResult = LabExtractData.DoData(_lstComInfo[3].LabMachineName, data, "port04");

                if (_lstObjResult != null)
                {
                    LstObjResuts = _lstObjResult;

                    foreach (ObjResults _rObject in LstObjResuts)
                    {
                        _controller.Save(_rObject);
                    }
                }


                //Auto send data to Comport
                if (LabMachines.lstMayXn2Chieu.Contains(_lstComInfo[3].LabMachineName))
                {
                    char[] c = data.ToCharArray();

                    if (Convert.ToInt32(c[0]).ToString() == "5")
                        _isLoop04 = true;

                    if (Convert.ToInt32(c[0]).ToString() == "4")
                        _isLoop04 = false;

                    System.Threading.Thread.Sleep(200);
                    if (_isLoop04)
                        LabCommon.AutoSend(comport04);
                }

                grdResults.DataSource = LstObjResuts;
            }
            catch { }

            txtTrangThai04.Invoke(new EventHandler(delegate
            {
                txtTrangThai04.Text = "Đang hoạt động...";
            }));
        }
        #endregion


        #region Comport05 - Receiving data
        void comport05_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            txtTrangThai05.Invoke(new EventHandler(delegate
            {
                txtTrangThai05.Text = "Đang nhận dữ liệu...";
            }));

            List<ObjResults> _lstObjResult = new List<ObjResults>();

            if (!comport05.IsOpen)
            {
                MessageBox.Show("Comport was closed.");
                return;
            }

            try
            {
                // Read all the data waiting in the buffer
                string data = comport05.ReadExisting();

                //Dubug Data
                rtxtResult01.Invoke(new EventHandler(delegate
                {
                    rtxtResult01.AppendText(data + "@END@");
                }));


                _lstObjResult = LabExtractData.DoData(_lstComInfo[4].LabMachineName, data, "port05");

                if (_lstObjResult != null)
                {
                    LstObjResuts = _lstObjResult;

                    foreach (ObjResults _rObject in LstObjResuts)
                    {
                        _controller.Save(_rObject);
                    }
                }


                //Auto send data to Comport
                if (LabMachines.lstMayXn2Chieu.Contains(_lstComInfo[4].LabMachineName))
                {
                    char[] c = data.ToCharArray();

                    if (Convert.ToInt32(c[0]).ToString() == "5")
                        _isLoop05 = true;

                    if (Convert.ToInt32(c[0]).ToString() == "4")
                        _isLoop05 = false;

                    System.Threading.Thread.Sleep(200);
                    if (_isLoop05)
                        LabCommon.AutoSend(comport05);
                }

                grdResults.DataSource = LstObjResuts;
            }
            catch { }

            txtTrangThai05.Invoke(new EventHandler(delegate
            {
                txtTrangThai05.Text = "Đang hoạt động...";
            }));
        }
        #endregion


        #region Comport06 - Receiving data
        void comport06_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            txtTrangThai06.Invoke(new EventHandler(delegate
            {
                txtTrangThai06.Text = "Đang nhận dữ liệu...";
            }));

            List<ObjResults> _lstObjResult = new List<ObjResults>();

            if (!comport06.IsOpen)
            {
                MessageBox.Show("Comport was closed.");
                return;
            }

            try
            {
                // Read all the data waiting in the buffer
                string data = comport06.ReadExisting();

                //Dubug Data
                rtxtResult01.Invoke(new EventHandler(delegate
                {
                    rtxtResult01.AppendText(data + "@END@");
                }));


                _lstObjResult = LabExtractData.DoData(_lstComInfo[5].LabMachineName, data, "port06");

                if (_lstObjResult != null)
                {
                    LstObjResuts = _lstObjResult;

                    foreach (ObjResults _rObject in LstObjResuts)
                    {
                        _controller.Save(_rObject);
                    }
                }


                //Auto send data to Comport
                if (LabMachines.lstMayXn2Chieu.Contains(_lstComInfo[5].LabMachineName))
                {
                    char[] c = data.ToCharArray();

                    if (Convert.ToInt32(c[0]).ToString() == "5")
                        _isLoop06 = true;

                    if (Convert.ToInt32(c[0]).ToString() == "4")
                        _isLoop06 = false;

                    System.Threading.Thread.Sleep(200);
                    if (_isLoop06)
                        LabCommon.AutoSend(comport06);
                }

                grdResults.DataSource = LstObjResuts;
            }
            catch { }

            txtTrangThai06.Invoke(new EventHandler(delegate
            {
                txtTrangThai06.Text = "Đang hoạt động...";
            }));
        }
        #endregion


        #region Comport07 - Receiving data
        void comport07_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            txtTrangThai07.Invoke(new EventHandler(delegate
            {
                txtTrangThai07.Text = "Đang nhận dữ liệu...";
            }));

            List<ObjResults> _lstObjResult = new List<ObjResults>();

            if (!comport07.IsOpen)
            {
                MessageBox.Show("Comport was closed.");
                return;
            }

            try
            {
                // Read all the data waiting in the buffer
                string data = comport07.ReadExisting();

                //Dubug Data
                rtxtResult01.Invoke(new EventHandler(delegate
                {
                    rtxtResult01.AppendText(data + "@END@");
                }));


                _lstObjResult = LabExtractData.DoData(_lstComInfo[6].LabMachineName, data, "port07");

                if (_lstObjResult != null)
                {
                    LstObjResuts = _lstObjResult;

                    foreach (ObjResults _rObject in LstObjResuts)
                    {
                        _controller.Save(_rObject);
                    }
                }


                //Auto send data to Comport
                if (LabMachines.lstMayXn2Chieu.Contains(_lstComInfo[6].LabMachineName))
                {
                    char[] c = data.ToCharArray();

                    if (Convert.ToInt32(c[0]).ToString() == "5")
                        _isLoop07 = true;

                    if (Convert.ToInt32(c[0]).ToString() == "4")
                        _isLoop07 = false;

                    System.Threading.Thread.Sleep(200);
                    if (_isLoop07)
                        LabCommon.AutoSend(comport07);
                }

                grdResults.DataSource = LstObjResuts;
            }
            catch { }

            txtTrangThai07.Invoke(new EventHandler(delegate
            {
                txtTrangThai07.Text = "Đang hoạt động...";
            }));
        }
        #endregion


        #region Comport08 - Receiving data
        void comport08_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            txtTrangThai08.Invoke(new EventHandler(delegate
            {
                txtTrangThai08.Text = "Đang nhận dữ liệu...";
            }));

            List<ObjResults> _lstObjResult = new List<ObjResults>();

            if (!comport08.IsOpen)
            {
                MessageBox.Show("Comport was closed.");
                return;
            }

            try
            {
                // Read all the data waiting in the buffer
                string data = comport08.ReadExisting();

                //Dubug Data
                rtxtResult01.Invoke(new EventHandler(delegate
                {
                    rtxtResult01.AppendText(data + "@END@");
                }));


                _lstObjResult = LabExtractData.DoData(_lstComInfo[7].LabMachineName, data, "port08");

                if (_lstObjResult != null)
                {
                    LstObjResuts = _lstObjResult;

                    foreach (ObjResults _rObject in LstObjResuts)
                    {
                        _controller.Save(_rObject);
                    }
                }


                //Auto send data to Comport
                if (LabMachines.lstMayXn2Chieu.Contains(_lstComInfo[7].LabMachineName))
                {
                    char[] c = data.ToCharArray();

                    if (Convert.ToInt32(c[0]).ToString() == "5")
                        _isLoop08 = true;

                    if (Convert.ToInt32(c[0]).ToString() == "4")
                        _isLoop08 = false;

                    System.Threading.Thread.Sleep(200);
                    if (_isLoop08)
                        LabCommon.AutoSend(comport08);
                }

                grdResults.DataSource = LstObjResuts;
            }
            catch { }

            txtTrangThai08.Invoke(new EventHandler(delegate
            {
                txtTrangThai08.Text = "Đang hoạt động...";
            }));
        }
        #endregion

        

        

     
       
        


    }
}